<%
// API Sidebar
//
// Parameters:
//  $0  A tag for the API group (searches for related APIs)

// Variables and data
var slug = env.slug;
var locale = env.locale;
var APIHref = '/' + locale + '/docs/Web/API';
var output = "";

// This is a hack. But to be able to use this macro in the /MDN/Kitchensink page
// we have to, unfortunately, pretend that our current slug is something
// that it's not. Otherwise you'll always get a `MacroPagesError` when using
// this macro on the kitchensink page.
if (slug.toLowerCase().startsWith('mdn/kitchensink')) {
  // Sorry, but it's important to be able to run this macro for CI.
  slug = 'Web/API/ServiceWorker';
}

// slug is not available in preview mode.
if (slug) {
var mainIF = slug.replace('Web/API/','').split('/')[0];
mainIF = mainIF.charAt(0).toUpperCase() + mainIF.slice(1);
var group = $0;
var hasTag = page.hasTag;
var htmlEscape = kuma.htmlEscape;
var rtlLocales = ['ar', 'he', 'fa'];

var webAPIData = web.getJSONData("InterfaceData");
if (group) {
  var webAPIGroups = web.getJSONData("GroupData");
}

var commonl10n = web.getJSONData("L10n-Common");

var text = {
    'Methods': mdn.getLocalString(commonl10n, 'Methods'),
    'Properties': mdn.getLocalString(commonl10n, 'Properties'),
    'Constructor': mdn.getLocalString(commonl10n, 'Constructor'),
    'Inheritance': mdn.getLocalString(commonl10n, 'Inheritance'),
    'Implemented_by': mdn.getLocalString(commonl10n, 'Implemented_by'),
    'Related': mdn.getLocalString(commonl10n, 'Related_pages').replace('$1', group),
    'translate': mdn.getLocalString(commonl10n, '[Translate]'),
    'title': mdn.getLocalString(commonl10n, 'TranslationCTA'),
    'Events': mdn.getLocalString(commonl10n, 'Events'),
};


// Collect all the things
var mainIFPages = await page.subpagesExpand('/en-US/docs/Web/API/' + mainIF);
var impl = webAPIData[0][mainIF] != undefined ? webAPIData[0][mainIF].impl : [];
var inh = webAPIData[0][mainIF] != undefined ? webAPIData[0][mainIF].inh : '';
var related = [];
var events = []
if (group && webAPIGroups[0][group]) {
  var rel_if = webAPIGroups[0][group].interfaces || [];
  var rel_met = webAPIGroups[0][group].methods || [];
  var rel_prop = webAPIGroups[0][group].properties || [];
  related = rel_if.concat(rel_met, rel_prop);
  var mainIfIndex = related.indexOf(mainIF);
  if (mainIfIndex !== -1) {
    related.splice(mainIfIndex, 1);
  }
  related.sort();
}

var properties = [];
var methods = [];
var ctors = [];
var events = [];
var inheritedIF = [];
var implementedBy = [];

function collect(pageList) {
  for (var i in pageList) {
    var aPage = pageList[i];
    if (hasTag(aPage, "Property")) {
        properties.push(aPage);
    }
    if (hasTag(aPage, "Method")) {
        methods.push(aPage);
    }
    if (hasTag(aPage, "Constructor")) {
        ctors.push(aPage);
    }
    if (hasTag(aPage, "Event")) {
        events.push(aPage);
    }
  }
}

collect(mainIFPages);

if (impl.length > 0) {
  for (var i = 0; i < impl.length; i++) {
    var implementPages = await page.subpagesExpand('/en-US/docs/Web/API/' + impl[i]);
    collect(implementPages);
  }
}


function APISort(a, b) {
  var aSplit = a.title.split('.');
  var a = aSplit[aSplit.length - 1];
  var bSplit = b.title.split('.');
  var b = bSplit[bSplit.length - 1];
  return a.toLowerCase().localeCompare(b.toLowerCase());
}

properties.sort(APISort);
methods.sort(APISort);
ctors.sort(APISort);
events.sort(APISort);

function getInheritance(inh) {
  if (inh.length > 0) {
    inheritedIF.push(inh);
    if (Object.prototype.hasOwnProperty.call(webAPIData[0], inh)) {
        var inh = webAPIData[0][inh].inh;
        getInheritance(inh);
    }
  }
}
getInheritance(inh);

function getImplementedBy(data) {
  for (var key in data) {
    if (Object.prototype.hasOwnProperty.call(data, key)
        && data[key].impl
        && data[key].impl.indexOf(mainIF) != -1) {
      implementedBy.push(key);
    }
  }
  implementedBy.sort();
}
getImplementedBy(webAPIData[0]);

// output helpers

var badges = {
  ExperimentalBadge : await template("ExperimentalBadge"),
  NonStandardBadge : await template("NonStandardBadge"),
  DeprecatedBadge : await template("DeprecatedBadge"),
  ObsoleteBadge : await template("ObsoleteBadge"),
}

function buildSublist(pages, title) {
  var result = '<li class="toggle"><details open><summary>' + title + '</summary><ol>';

  for (var i in pages) {
    var aPage = pages[i];
    var url = aPage.url.replace('en-US', locale);
    var titleSplit = htmlEscape(aPage.title).split('.'); // Two cases, as sometimes the interface name is forgotten in the title:
    var title = titleSplit[titleSplit.length - 1];       // "WebGLRenderingContext.activeTexture()" and "activeTexture()" should both become "activeTexture()"

    var translated = false;
    if (locale != 'en-US') {
        aPage.translations.forEach(function(translation){
            if(translation.locale === locale) {
                url = translation.url;
                titleSplit = htmlEscape(translation.title).split('.');
                title = titleSplit[titleSplit.length - 1];
                translated = true;
            }
        });
    }

    // Event pages have a title like "Interface: eventname event" which looks silly
    // in the sidebar. So for event pages we use the slug, which is supposed to be
    // in the form "eventname_event", and split off "_event" to leave us (hopefully)
    // with just "eventname" for the link text.
    if (hasTag(aPage, 'Event')) {
        title = aPage.slug.split('/').pop();
        if (title.endsWith('_event')) {
            title = title.slice(0,-6);
        }
    }

    result += '<li>';

    if (hasTag(aPage, 'Experimental')) {
        result += badges.ExperimentalBadge;
    }

    if (hasTag(aPage, 'Non-standard') || hasTag(aPage, 'Non Standard')) {
        result += badges.NonStandardBadge;
    }

    if (hasTag(aPage, 'Deprecated')) {
        result += badges.DeprecatedBadge;
    }

    if (hasTag(aPage, 'Obsolete')) {
        result += badges.ObsoleteBadge;
        result += '<s class="obsoleteElement">';
    }

    if (rtlLocales.indexOf(locale) != -1) {
        result += '<bdi>';
    }

    if (slug == aPage.slug) {
        result += '<em><code>' + title + '</code></em>'
    } else {
        result += web.smartLink(url, null, `<code>${title}</code>`, APIHref, null, "APIRef");
    }

    if (rtlLocales.indexOf(locale) != -1) {
        result += '</bdi>';
    }

    if (hasTag(aPage, 'Obsolete')) {
        result += '</s>';
    }

    result += '</li>';
  }

  result += '</ol></details></li>';

  return result;
}

function buildIFList(interfaces, title) {
  var result = '<li class="toggle"><details open><summary>' + title + '</summary><ol>';

  for (var i = 0; i < interfaces.length; i++) {
    var url = interfaces[i].replace('()', '').replace('.', '/');
    result += `<li>${web.smartLink(APIHref + '/' + url, null, `<code>${interfaces[i]}</code>`, APIHref, null, "APIRef")}</li>`;
  }

  result += '</ol></details></li>';

  return result;
}

// output
output = '<section id="Quick_links"><ol>';
if (group && webAPIGroups[0][group] && webAPIGroups[0][group].overview) {
  output += `<li><strong>${web.smartLink(APIHref + '/' + webAPIGroups[0][group].overview[0].replace(/ /g, '_'), null, webAPIGroups[0][group].overview[0], APIHref, null, "APIRef")}</strong></li>`;
}

output += `<li><strong>${web.smartLink(APIHref + '/' + mainIF, null, `<code>${mainIF}</code>`, APIHref, null, "APIRef")}</strong></li>`;

if (ctors.length > 0) {
  output += buildSublist(ctors, text['Constructor']);
}

if (properties.length > 0) {
  output += buildSublist(properties, text['Properties']);
}
if (methods.length > 0) {
  output += buildSublist(methods, text['Methods']);
}
if (events.length > 0) {
  output += buildSublist(events, text['Events']);
}
if (inh.length > 0) {
  output += buildIFList(inheritedIF, text['Inheritance']);
}
if (implementedBy.length > 0) {
  output += buildIFList(implementedBy, text['Implemented_by']);
}

if (related.length > 0) {
  output += buildIFList(related, text['Related']);
}

output += '</ol></section>';
}
%>

<%-output%>
